package com.sync.syncmasterdata.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecond",
        transactionManagerRef="transactionManagerSecond",
        basePackages= {"com.sync.syncmasterdata.customer.repository.u8rep", "com.sync.syncmasterdata.vendor.repository.u8rep", "com.sync.syncmasterdata.product.repository.u8"})//设置dao（repo）所在位置
public class SecondConfig {
    @Autowired
    @Qualifier("dataSourceTwo")
    private DataSource secondDataSource;

//    @Autowired
//    @Qualifier("vendorProperties")
//    private Map<String, Object> vendorProperties;

    @Resource
    private Properties jpaProperties;


    @Primary
    @Bean(name = "entityManagerFactorySecond")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
                .dataSource(secondDataSource)
//                .properties(vendorProperties)
                .packages("com.sync.syncmasterdata.customer.entity.u8","com.sync.syncmasterdata.vendor.entity.u8","com.sync.syncmasterdata.product.entity.u8")
                .persistenceUnit("secondPersistenceUnit")
                .build();
        entityManagerFactory.setJpaProperties(jpaProperties);
        return entityManagerFactory;
    }

    @Primary
    @Bean(name = "entityManagerSecond")
    public EntityManager entityManagerSecond(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecond(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "transactionManagerSecond")
    PlatformTransactionManager transactionManagerSecond(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
    }

}
